import { defineComponent, watch, ref, computed } from 'vue'

import { ElUpload, ElImage } from 'element-plus'
import 'element-plus/dist/index.css';

import './style.scss'
import myMeta from './meta'

export const meta = myMeta
/**
 * 支持配置：
 * 内容限制格式，valid
 * 字数限制，textRange
 * 引导提示文案，placeholder
 */
export default defineComponent({
  name: 'ImageModule',
  props: {
    type: {
      type: String,
      default: ''
    },
    field: {
      type: String,
      default: ''
    },
    value: {
      type: [Array, String],
      default: () => []
    },
    placeholder: {
      type: String,
      default: '请填写'
    },
    textRange: {
      type: Object,
      default: () => {
        return {
          max: {
            placeholder: '500',
            value: 500
          },
          min: {
            placeholder: '0',
            value: 0
          }
        }
      }
    },
    valid: {
      type: String,
      default: ''
    },
    readonly: {
      type: Boolean,
      default: false
    }
  },
  emits: ['blur', 'focus', 'input', 'change'],
  setup(props, { emit }) {
    const focusFlag = ref(false)
    const initial = props.textRange.max.value - props.value.length
    const getLeftTextNumber = ref(initial)
    const fileList = ref([])
    const fileViewList = computed(() => {
      return fileList.value.map((item) => window.$app?.fileBaseUrl + item.filename)
    })

    // watch(
    //   () => props.value,
    //   (val) => {
    //     if (val) {
    //       let arr = []
    //       let viewArr = []
    //       if (Array.isArray(props.value) && props.value.length) {
    //         props.value.forEach((item) => {
    //           arr.push(item.filename)
    //           viewArr.push(window.$app?.fileBaseUrl + item.filename)
    //         })
    //       } else if (props.value && typeof props.value === 'string') {
    //         arr = props.value.split(',')
    //         viewArr = arr.map((item) => window.$app?.fileBaseUrl + item)
    //       }
    //       // fileList.value = arr
    //       fileViewList.value = viewArr
    //     }
    //   }
    // )

    const beforeUpload = (file) => {
      console.log(file)
      const isJPG = file?.type === 'image/jpeg'
      const isPNG = file?.type === 'image/png'
      const isJPEG = file?.type === 'image/jpeg'
      const isGIF = file?.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isPNG && !isJPEG && !isGIF && !isJPG) {
        return false
      }
     
      if (!isLt2M) {
        window.$ui.msg('上传文件大小不能超过 5MB!')
        return false
      }
      return true
    }

    const handleRemove = (uploadFile, uploadFiles) => {
      console.log(uploadFile)
      uploadFile?.response?.fileInfos?.forEach((item) => {
        fileList.value = fileList.value.filter((file) => file?.filename !== item?.filename)
      })
      emit('change', {
        key: props.field,
        value: fileList.value
      })
    }
    
    const handlePictureCardPreview = (uploadFile) => {
      // dialogImageUrl.value = uploadFile.localPath
      // dialogVisible.value = true
    }
    const onChange = (uploadFile, uploadFiles) => {
      console.log(uploadFile, uploadFiles)
      const key = props.field
      uploadFile?.data?.forEach((item) => {
        fileList.value.push({
          ...item
        })
      })
      // const maxLength = get(props, 'textRange.max.value')
      // if (
      //   get(props, 'valid') === 'n' &&
      //   maxLength &&
      //   e.target.value.toString().length > maxLength
      // ) {
      //   e.target.value = e.target.value.slice(0, props.textRange.max.value)
      // }
      // if (['m', 'idcard', 'e', 'licensePlate'].includes(props.valid)) {
      //   e.target.value = e.target.value.replace(/\s+/g, '')
      // }

      emit('change', {
        key,
        value: fileList.value // .map((item) => item.localPath)
      })
    }

    let uploadData = {
      unZip: true,
      frameNum: 1,
      userId: window.$app.user.userId,
      priority: '7',
      sourceDel: '0',
      ttlTimes: '7',
      timePoint: '00:00:05'
    }
    let uploadHeaders = {
      branchCode: window.$app.user.branchCode || 'twpaas',
      'X-Client-Language': 'zh_CN',
      'Access-Token': window.$app.user.token,
      'X-User-Account': window.$app.user.userId
    }

    return {
      props,
      focusFlag,
      getLeftTextNumber,
      onChange,
      handlePictureCardPreview, 
      handleRemove,
      beforeUpload,
      uploadData,
      uploadHeaders,
      fileList,
      fileViewList
    }
  },
  render() {
    const { beforeUpload, onChange, handlePictureCardPreview, handleRemove, props, uploadData, uploadHeaders, readonly, fileList, fileViewList } = this

    return (
      <div>
         {readonly&&(<div class="uploadfile-list">
        {fileViewList.map((item, index) => {
            return (
              <div
                key={index}
                class={['uploadfile-item']}
              >
                <ElImage
                  style="width: 100px; height: 100px"
                  src={item}
                  zoom-rate={1.2}
                  max-scale={7}
                  min-scale={0.2}
                  preview-src-list={fileViewList}
                  initial-index={index}
                  fit="cover"
                />
              </div>
            )
          })}
        </div>)}
        <ElUpload
          accept="image/*"
          action={window.$app.fileUploadUrl}
          list-type="picture-card"
          on-preview={handlePictureCardPreview}
          on-success={onChange}
          before-upload={beforeUpload}
          on-remove={handleRemove}
          disabled={readonly}
          headers={uploadHeaders}
        >
          <i class="iconfont icon-chuangjian"></i>
        </ElUpload>
      </div>
    )
  }
})
